# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 11:28:09 2018

@author: jiujiujiu

http://bitianxia.cn/
币天下

"""

import requests
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_KXun(url):
    text = get_html_text(url)
    if not text:
        return None
    text = eval(get_html_text(url))
    data = text['articles']
    dates = [date['published_time'][:10] for date in data]
    return dates


def count_process_one():  # 快讯
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'http://bitianxia.cn/portal/list/index/id/6.html?page={}&ids=6'
        url = url.format(a)
        dates = get_dates_KXun(url)
        if not dates:
            break
        print('----币天下快讯获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_two():  # 新闻
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'http://bitianxia.cn/portal/list/index/id/7.html?page={}&ids=25'
        url = url.format(a)
        dates = get_dates_KXun(url)
        if not dates:
            break
        print('----币天下新闻最新获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '币天下'
    t1 = count_process_one()
    t2 = count_process_two()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
